// pages/intelligence-control/intelligence-control.js
import {
  ab2hex,
  inArray
} from "../../utils/util"
import {
  generateData,
  getServiceUUIDs
} from "../../utils/BLEUtil"
const filterName = 'TEMP'
Component({
  properties: {
    settingType: {
      type: String,
      value: 'color'
    }
  },
  system: 'android',
  /**
   * 页面的初始数据
   */
  data: {
    tabs: [{
      name: '统一',
      type: 'unify',
      id: '00'
    }, {
      name: '模块一',
      type: 'one',
      id: '01'
    }, {
      name: '模块二',
      type: 'two',
      id: '02'
    }],
    curArea: 0,
    lightValue: 0,
    colorMap: {
      '0': [{
        color: '#cf4994',
        imgURL: '/images/dynamic/1.jpg',
        text: '呼吸',
        id: '01'
      }, {
        color: '#9c6845',
        imgURL: '/images/dynamic/2.jpg',
        text: '跳变',
        id: '02'
      }, {
        color: '#8f33aa',
        imgURL: '/images/dynamic/5.jpg',
        text: '闪变',
        id: '03'
      }, {
        color: '#57b8b3',
        imgURL: '../../images/dynamic/4.jpg',
        text: '渐变',
        id: '04'
      }, {
        color: '#3481f7',
        imgURL: '../../images/dynamic/3.jpg',
        text: '锁定',
        id: '05'
      }, {
        color: '#9ac555',
        imgURL: '../../images/dynamic/6.jpg',
        text: '熄灭',
        id: '06'
      }],
      '1': [{
        color: '#cf4994',
        imgURL: '/images/dynamic/7.jpg',
        text: '跑马',
        id: '01'
      }, {
        color: '#9c6845',
        imgURL: '/images/dynamic/8.jpeg',
        text: '追逐',
        id: '02'
      }, {
        color: '#8f33aa',
        imgURL: '/images/dynamic/9.jpg',
        text: '呼吸',
        id: '03'
      }, {
        color: '#57b8b3',
        imgURL: '../../images/dynamic/4.jpg',
        text: '渐变',
        id: '04'
      }, {
        color: '#3481f7',
        imgURL: '../../images/dynamic/3.jpg',
        text: '锁定',
        id: '05'
      }, {
        color: '#9ac555',
        imgURL: '../../images/dynamic/6.jpg',
        text: '熄灭',
        id: '06'
      }],
      '2': [{
        color: '#8f33aa',
        imgURL: '/images/dynamic/9.jpg',
        text: '呼吸',
        id: '01'
      }, {
        color: '#9c6845',
        imgURL: '/images/dynamic/2.jpg',
        text: '跳变',
        id: '02'
      }, {
        color: '#8f33aa',
        imgURL: '/images/dynamic/5.jpg',
        text: '闪变',
        id: '03'
      }, {
        color: '#57b8b3',
        imgURL: '../../images/dynamic/4.jpg',
        text: '渐变',
        id: '04'
      }, {
        color: '#3481f7',
        imgURL: '../../images/dynamic/3.jpg',
        text: '锁定',
        id: '05'
      }, {
        color: '#9ac555',
        imgURL: '../../images/dynamic/6.jpg',
        text: '熄灭',
        id: '06'
      }]
    },
    curDynamic: null,
    colorList: [],

    // 蓝牙模块
    discoveryStarted: false,
    advertiseStart: false,
    discoveryReady: false,
    advertiseReady: false,
    nextSeq: 16,
    payload: '',
    servers: [],
    serverId: '',
    filterName: filterName,
    receiveDataList: []
  },

  lifetimes: {
    attached() {
      this.setData({
        colorList: this.data.colorMap[this.data.curArea]
      })

      this.initSystemInfo()
      this.initPayload();
      this.initAdvertiseAdapter()
      this.initDiscoveryAdapter()
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
      this.stopAdvertising()
      this.stopBluetoothDevicesDiscovery()
      this.data.servers.forEach(server => {
        server.close()
      })
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    tabSelect(e) {
      const curArea = e.currentTarget.dataset.id
      this.setData({
        curArea,
        colorList: this.data.colorMap[curArea]
      })
    },
    changeLightColor(e) {
      const colorArr = e.detail.pickColor
      console.log('接收到颜色值，开始发送广播包:', colorArr, '当前模块：', this.data.curArea)
      this.stopAdvertising() // 先停止
      this.startSendAndDiscovery(this.encodeRGB(colorArr[0],colorArr[1],colorArr[2]), '27',this.data.curArea) // 再开始
    },
    changeLight(e) {
      this.setData({
        lightValue: e.detail.value
      })
      console.log('亮度调节：', e.detail.value)
    },
    handleDynamicChange(e) {
      this.setData({
        curDynamic: e.currentTarget.dataset.id
      })
      console.log('动态色彩调节：', e.currentTarget.dataset.id)
      console.log('改变动态色彩，开始发送广播包:', this.data.curDynamic)
      console.log('当前模块:', this.data.curArea)
      this.stopAdvertising() // 先停止
      this.startSendAndDiscovery(e.currentTarget.dataset.id, '36',this.data.curArea) // 再开始
    },

    // 蓝牙模块
    initBluetoothDevicesDiscovery() {
      if (this.data.discoveryStarted) {
        return
      }
      if (!this.data.discoveryStarted) {
        wx.startBluetoothDevicesDiscovery({
          allowDuplicatesKey: true,
          powerLevel: "high",
          // services: ['11:22:33:44:55:66'],
          success: (res) => {
            console.log('startBluetoothDevicesDiscovery success! ', res)
            this.setData({
              discoveryReady: true
            })
          },
          fail: (res) => {
            console.log('startBluetoothDevicesDiscovery failed! ', res)
          }
        })
      }
    },
    startBluetoothDevicesDiscovery() {
      if (this.data.discoveryStarted)
        return
      this.onBluetoothDeviceFound()
      this.setData({
        "discoveryStarted": true
      })

    },
    // createBLEPeripheralServer() {
    //   wx.createBLEPeripheralServer().then(res => {
    //     console.log('createBLEPeripheralServer', res)
    //     this.data.servers.push(res.server)
    //     this.server = res.server
    //     this.setData({
    //       advertiseReady: true,
    //       serverId: this.server.serverId
    //     })
    //   })
    // },
    initSystemInfo() {
      const {
        system
      } = wx.getSystemInfoSync();
      console.log('system', system)
      this.system = system
    },
    initPayload() {
      wx.getStorage({
        key: 'payload',
        success: (res) => {
          if (res.data) {
            this.setData({
              payload: res.data
            })
          }
        }
      })
    },
    initAdvertiseAdapter() {
      wx.openBluetoothAdapter({
        mode: 'peripheral',
        success: (res) => {
          console.log('initAdvertiseAdapter success', res)
          this.createBLEPeripheralServer()
        },
        fail: (res) => {
          console.log("initAdvertiseAdapter ble unavailable!", res)
          // wx.showModal({
          //   content:'初始化失败',
          //   cancelColor: 'cancelColor',
          // })
        }
      })
    },

    encodeRGB(r, g, b) {
      var rgb = (r >> 5 << 5) + (g >> 5 << 2) + (b >> 6);
      var res = rgb.toString(16);
      if (res.length == 1) {
        return '0'+res;
      }else{
        return res;
      }
    },

    encodeIdx(idx) {
      console.log('idx:',idx)
      var i = 16 + idx;
      return i.toString(16);
    },

    startSendAndDiscovery(c4, c5, c6) {
      console.log('这里是发送广播包的函数:',c4, c5, c6)
      // let payload = this.data.payload
      let payload = '112256' + c4 + c5 + '0'+ c6
      console.log('--------->', payload)
      payload = payload.replace(/\s+/g, '')
      if (!payload || payload.length === 0) {
        wx.showModal({
          content: '请填写payload',
          cancelColor: 'cancelColor',
        })
        return
      }
      wx.setStorage({
        data: payload,
        key: 'payload',
      })

      if (!this.data.advertiseReady) {
        wx.showModal({
          content: '初始化未成功',
          cancelColor: 'cancelColor',
        })
        console.log('发送初始化失败')
        this.initAdvertiseAdapter()
      }
      const isIos = this.system.indexOf('iOS') >= 0
      const actPayload = generateData(payload, isIos);
      this.startAdvertising(actPayload)
      // 1.5秒后停止广播
      setTimeout(()=> {
        console.log('停止广播')
        this.stopAdvertising()
      }, 1500)
    },
    initDiscoveryAdapter() {
      wx.openBluetoothAdapter({
        // mode: 'peripheral',
        success: (res) => {
          console.log('initDiscoveryAdapter success', res)
          this.initBluetoothDevicesDiscovery();
        },
        fail: (res) => {
          console.log("initDiscoveryAdapter ble unavailable!", res)
          // wx.showModal({
          //   content:'初始化失败',
          //   cancelColor: 'cancelColor',
          // })
        }
      })
    },
    stopAdvertising() {
      if (this.server) {
        this.server.stopAdvertising()
        this.setData({
          advertiseStart: false
        })
      }

    },
    stopBluetoothDevicesDiscovery() {
      if (!this.data.discoveryStarted)
        return
      this.setData({
        "discoveryStarted": false
      })
      wx.offBluetoothDeviceFound()
    },
    onBluetoothDeviceFound() {
      const filterName = this.data.filterName
      wx.onBluetoothDeviceFound((res) => {
        res.devices.forEach(device => {
          if (!device.localName || device.localName != filterName) {
            return
          }
          const foundDevices = this.data.devices
          const idx = inArray(foundDevices, 'deviceId', device.deviceId)
          const data = {}
          if (idx === -1) {
            data[`devices[${foundDevices.length}]`] = device
          } else {
            data[`devices[${idx}]`] = device
          }
          let hexData = ab2hex(device.advertisData)
          hexData = hexData.substring(4)
          device.data = hexData
          const myDate = new Date();
          const time = myDate.toLocaleTimeString() + " " + myDate.getMilliseconds()
          const receiveData = {
            time,
            data: hexData
          }
          let lastDataList = this.data.receiveDataList
          if (lastDataList.length > 100) {
            lastDataList = lastDataList.slice(0, 100)
          }
          this.setData({
            receiveDataList: [receiveData, ...lastDataList]
          })
        })
      })
    },
    createBLEPeripheralServer() {
      wx.createBLEPeripheralServer().then(res => {
        console.log('createBLEPeripheralServer', res)
        this.data.servers.push(res.server)
        this.server = res.server
        this.setData({
          advertiseReady: true,
          serverId: this.server.serverId
        })
      })
    },
    startAdvertising(actPayload) {
      const isIos = this.system.indexOf('iOS') >= 0
      const isIos13 = isIos && this.system.indexOf('13.') >= 0
      console.log('actPayload', actPayload)
      const uuids = getServiceUUIDs(actPayload, isIos13)
      this.server.startAdvertising({
        advertiseRequest: {
          connectable: true,
          deviceName: isIos ? '11' : '',
          serviceUuids: isIos ? uuids : [],
          manufacturerData: isIos ? [] : [{
            manufacturerId: '0x00C7',
            manufacturerSpecificData: actPayload,
          }]
        },
        powerLevel: 'high'
      }).then(res => {
        console.log('startAdvertising', res)
        this.setData({
          advertiseStart: true
        })
      }, res => {
        this.setData({
          advertiseStart: false
        })
        console.log("fail: ", res)
      })
    },

  }
})